import {useContext, useMemo} from 'react';
import Context from '../context';
import * as SchoolApi from '../apis/school';
import * as MemberApi from '../apis/member';
import * as CheckInApi from '../apis/checkin';
import * as CourseAPi from '../apis/course';

const checkInTypeMap = {
  '1': '活动类',
  '2': '讲座类',
  '3': '内部培训',
  '4': '团建类',
  '5': '公众号运营',
  '6': '成员服务分',
  '7': '互帮互助分',
  '8': '成员素质分',
};

const useGlobal = () => {

  const {global, setGlobal} = useContext(Context);

  // schoolList hash 表
  const schoolListMap = useMemo(() => {
    return global.schoolList?.reduce((res, item) => {
      res[item.id] = item;
      return res;
    }, {});
  }, [global.schoolList]);

  const memberListMap = useMemo(() => {
    return global.memberList.reduce((res, item) => {
      res[item.id] = item;
      return res;
    }, {});
  }, [global.memberList]);

  const updateSchoolList = async (list) => {
    if (list) {
      setGlobal(draft => {
        draft.schoolList = list;
      });
    } else {
      const res = await SchoolApi.getList(global.login?.token || '');
      setGlobal(draft => {
        draft.schoolList = res.data.data.list;
      });
    }
  };

  const updateMemberList = async (list) => {
    if (list) {
      setGlobal(draft => {
        draft.schoolList = list;
      });
    } else {
      const list = await MemberApi.getList(global.login?.token || '');
      setGlobal(draft => {
        draft.memberList = list;
      });
    }
  };

  const updateCheckInTypeList = async (list) => {
    if (list) {
      setGlobal(draft => {
        draft.schoolList = list;
      });
    } else {
      const res = await CheckInApi.getTypeList(global.login?.token || '');
      setGlobal(draft => {
        draft.checkInTypeList = res.data.data.list;
      });
    }
  };

  const updateCourseTypeList = async (list) => {
    if (list) {
      setGlobal(draft => {
        draft.courseTypeList = list;
      });
    } else {
      const res = await CourseAPi.listLessonType(global.login?.token || '');
      setGlobal(draft => {
        draft.courseTypeList = res.data.list;
      });
    }
  };

  const setLogin = (data) => {
    setGlobal(draft => {
      draft.login = data;
    });
  };

  const getSchoolById = (id) => schoolListMap[id];
  const getMemberById = (id) => memberListMap[id];
  const getCheckInTypeById = id => checkInTypeMap[id];

  const effect = {
    setLogin,
    updateSchoolList,
    updateMemberList,
    updateCheckInTypeList,
    updateCourseTypeList,
    getSchoolById,
    getMemberById,
    getCheckInTypeById
  };

  return {
    state: global,
    effect
  };
};

export default useGlobal;